const nameSpace = 'the-darcrands-little-chat-room-user'

class User {
    get() {
        const id = window.localStorage.getItem(`${nameSpace}-id`)
        const name = window.localStorage.getItem(`${nameSpace}-name`)
        const avatar = window.localStorage.getItem(`${nameSpace}-avatar`)
        if (id && name && avatar) {
            return { id, name, avatar }
        } else {
            return null
        }
    }

    set(name, avatar) {
        const id = randomStr() + new Date().getTime()
        window.localStorage.setItem(`${nameSpace}-id`, id)
        window.localStorage.setItem(`${nameSpace}-name`, name)
        window.localStorage.setItem(`${nameSpace}-avatar`, avatar)
        return { id, name, avatar }
    }
}

/**
 * @name randomStr
 * @desc 随机字符串
 * @param {Number} len - 字符串长度
 */
function randomStr(len = 16) {
    const string = '0123456789abcdefghijklmnopqrstuvwxyz'
    const l = string.length
    let str = ''
    for (let i = 0; i < len; i++) {
        const index = Math.ceil((Math.random() * 100) % l)
        str += string[index]
    }
    return str
}

/**
 * @param {Object|Number} date 日期对象|时间戳
 * @param {String} formate 日期格式 'yyy'表示年份,'mmm'表示月份,'ddd'表示日期,'www'表示星期几,'hh'表示小时,'mm'表示分钟,'ss'表示秒
 */

function dateFormate(date, formate = 'yyy-mmm-ddd 星期www hh:mm:ss') {
    if (!date) {
        throw new Error('first param "date" is missing')
    } else if (!(date instanceof Date || date > 0)) {
        throw new Error('first param "date" should be a "object Date()" or "timeStamp"')
    }
    date = date instanceof Date ? date : new Date(date)
    const d = {
        yyy: date.getFullYear(),
        mmm: date.getMonth() + 1,
        ddd: date.getDate(),
        www: ['日', '一', '二', '三', '四', '五', '六'][date.getDay()],
        hh: date.getHours(),
        mm: date.getMinutes(),
        ss: date.getSeconds()
    }
    const zero = num => (num > 9 ? num : `0${num}`)
    let formateStr = formate
    for (const key in d) {
        if (d.hasOwnProperty(key)) {
            const reg = new RegExp(`${key}`)
            formateStr = formateStr.replace(reg, key === 'www' ? d[key] : zero(d[key]))
        }
    }
    return formateStr
}

export { User, randomStr, dateFormate }
